package com.sxhuayuan.parking.controller.member;

import com.alibaba.fastjson.JSON;
import com.sxhuayuan.parking.compenent.Filter;
import com.sxhuayuan.parking.compenent.Message;
import com.sxhuayuan.parking.compenent.Page;
import com.sxhuayuan.parking.compenent.Pageable;
import com.sxhuayuan.parking.compenent.domain.KeyValue;
import com.sxhuayuan.parking.compenent.web.RespMessage;
import com.sxhuayuan.parking.compenent.web.RespMessage.Status;
import com.sxhuayuan.parking.config.PayMode;
import com.sxhuayuan.parking.config.Platform;
import com.sxhuayuan.parking.dto.CreateOrderDTO;
import com.sxhuayuan.parking.dto.ParkFeeCacheBean;
import com.sxhuayuan.parking.entity.*;
import com.sxhuayuan.parking.plugin.payment.ResultPayJsonData;
import com.sxhuayuan.parking.plugin.payment.WxPayPlugin;
import com.sxhuayuan.parking.service.*;
import com.sxhuayuan.parking.utils.DeviceUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller("memberOrderController")
@RequestMapping("/member/order")
public class OrderController extends BaseController {

	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	OrderService service;
	@Autowired
	MemberService memberService;
	@Autowired
	MemberCarPlateService carPlateService;
	@Autowired
	ParkChannelService exitService;
	@Autowired
	ParkingLotService lotService;
	@Autowired
	ParkingInService inService;
	@Autowired
	OrderService orderService;
	@Autowired
	ParkFeeCacheService parkFeeCacheService;
	@Autowired
	WxPayPlugin wxpayPlugin;

	/** 账单 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String bill(Model model) {
		return "bill/bill";
	}

	/** 账单 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public RespMessage billList(@RequestBody Pageable pageable) {
		Member member = memberService.getCurrent();
		// data.setMemberId(member.getId());
		pageable.addFilter(Filter.eq("memberId", member.getId()));
		return RespMessage.builder().success().setDatas(service.findPage(pageable)).build();
	}

	/**
	 * 支付下单
	 * 
	 * @param dto
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	@ResponseBody
	public RespMessage create(@Validated @RequestBody CreateOrderDTO dto, HttpServletRequest request) {
		log.debug("下单: {}", JSON.toJSONString(dto));
		ParkingIn in = inService.findByUniqueId(dto.getUniqueId());
		if (in == null) {
			return RespMessage.error(Status.VALID_ERR, Message.CAR_NO_ENTRANCE_RECORD);
		}
		ParkFeeCacheBean parkFee = parkFeeCacheService.get(in.getUniqueId());
		if (parkFee == null) {
			return RespMessage.error(Status.VALID_ERR, Message.ORDER_TIMEOUT);
		}
		ParkChannel exit = null;
		String exitSn = getExitSnFromSession();
		if (!StringUtils.isEmpty(exitSn)) {
			exit = exitService.findBySn(exitSn);
		}
		Member current = memberService.getCurrent();

		ResultPayJsonData payJsonData = null;
		// 有出口为出口支付，否则为预支付
		Order.Method method = exit != null ? Order.Method.exit : Order.Method.prepay;
		Platform platform = getPlatform(request);
		String ip = DeviceUtil.getRemortIP(request);

		Order order = orderService.create(in, parkFee, current, platform, PayMode.jssdk, method, ip, dto.getRemark());
		try {
			Long exitId = null;
			if (exit != null) {
				exitId = exit.getId();
			}
			service.update(order, platform, PayMode.jssdk, current, exitId, dto.getRemark());
			payJsonData = wxpayPlugin.unified(order);
			order.setTradeNo(payJsonData.getTradeNo());
			service.update(order);
			return RespMessage.builder().success().setDatas(payJsonData).build();
		} catch (Exception e) {
			log.error("", e);
			return RespMessage.error(Status.ERROR, "下单失败：" + e.getMessage());
		}
	}

   //	统计可以开发票订单的车场列表
	@GetMapping("/parking/list")
	@ResponseBody
	public RespMessage getParkingList(){
		Member member = memberService.getCurrent();
		List<KeyValue> list = orderService.findParkingListByMember(member);
		return RespMessage.success(list);
	}

	@PostMapping("/invoice/order")
	@ResponseBody
	public RespMessage invoiceOrderList(@RequestBody Pageable pageable){
		//使用pageable中的searchValue属性装车场sn
		String sn = pageable.getSearchValue();
		if (StringUtils.isEmpty(sn)){
			return RespMessage.error("缺少车场参数");
		}
		ParkingLot parkingLot = lotService.findBySn(sn);
		if (parkingLot==null){
			return RespMessage.error("车场不存在");
		}
		Member member = memberService.getCurrent();
		Page<Order> page = orderService.findPage(pageable, member, parkingLot);
		return RespMessage.success(page);
	}
}
